<?php
require_once 'array.php';
// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

use service\DataService;
use service\NodeService;
use think\Response;
use think\Db;
use think\exception\HttpResponseException;

/**
 * 打印输出数据到文件
 * @param mixed $data 输出的数据
 * @param bool $force 强制替换
 * @param string|null $file
 */
function p($data, $force = false, $file = null)
{
    is_null($file) && $file = env('runtime_path') . date('Ymd') . '.txt';
    $str = (is_string($data) ? $data : ((is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true))) . PHP_EOL;
    $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
}


/**
 * 日期格式标准输出
 * @param string $datetime 输入日期
 * @param string $format 输出格式
 * @return false|string
 */
function format_datetime($datetime, $format = 'Y年m月d日 H:i:s')
{
    return date($format, strtotime($datetime));
}

/**
 * UTF8字符串加密
 * @param string $string
 * @return string
 */
function encode($string)
{
    list($chars, $length) = ['', strlen($string = iconv('utf-8', 'gbk', $string))];
    for ($i = 0; $i < $length; $i++) {
        $chars .= str_pad(base_convert(ord($string[$i]), 10, 36), 2, 0, 0);
    }
    return $chars;
}

/**
 * UTF8字符串解密
 * @param string $string
 * @return string
 */
function decode($string)
{
    $chars = '';
    foreach (str_split($string, 2) as $char) {
        $chars .= chr(intval(base_convert($char, 36, 10)));
    }
    return iconv('gbk', 'utf-8', $chars);
}

/**
 * 下载远程文件到本地
 * @param string $url 远程图片地址
 * @return string
 */
function local_image($url)
{
    return \service\FileService::download($url)['url'];
}

/**
 * 判断是否是空字符串
 *
 * @since v1.0.0
 * @author ranj
 * @param string $string
 * @return bool
 */
function is_null_or_empty($string)
{
    if (is_null($string)) {
        return true;
    }

    if (is_array($string) && !count($string)) {
        return true;
    }

    if (!is_string($string) && $string) {
        return false;
    }
    return is_null($string) || $string === '';
}

/**
 * Json Decode 安全的解析
 *
 * @since v1.0.0
 * @author ranj
 * @param string|array $data
 * @param bool $assoc
 * @return array|object
 */
function maybe_json_decode($data, $assoc = true)
{
    if (!$data) {
        return $assoc ? array() : new stdClass();
    }

    if (is_array($data) || is_object($data)) {
        return $data;
    }

    if (is_string($data)) {
        $result = json_decode($data, $assoc);
        if (!$result) {
            return $assoc ? array() : new stdClass();
        }
        return $result;
    }

    return array();
}

/**
 * json_encode
 *
 * @param $data
 * @return false|string
 */
function maybe_json_encode($data)
{
    if (array_is($data)) {
        return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }

    if (!$data) {
        return json_encode(array(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);;
    }

    if (is_string($data)) {
        return $data;
    }

    return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false)
{
    return request()->ip($type, $adv);
}

/**
 * 正整数转换
 *
 * @param string $val
 * @return float|int
 */
function absint($val)
{
    return abs(intval($val));
}

/**
 * Notes: 返回json
 * @param int $code
 * @param string $msg
 * @param array $data
 * @return \think\response\Json
 */
function base_return_json($code = 500, $msg = '', $data = [])
{
    $response = json(['code' => $code, 'msg' => $msg, 'data' => $data], 200, [
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Methods' => 'POST, PUT, GET, OPTIONS, DELETE',
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Allow-Headers' => 'x-auth-token, x-requested-with,Authorization,Origin, Accept, Content-Type,x-xsrf-token'
    ]);
    return $response;
}

/**
 * Notes: 返回错误json
 * @param string $errmsg
 * @return \think\response\Json
 */
function base_return_error_json($errmsg = '') {
    $response = base_return_json(10005, $errmsg);
    return $response;
}

/**
 * Notes: 返回成功json
 * @param array $data
 * @return \think\response\Json
 */
function base_return_success_json($data = [],$code=10000) {
    $response = base_return_json($code, \think\facade\Lang::get('successful'), $data);
    return $response;
}

/**
 * Notes: 返回404json
 * @return \think\response\Json
 */
function base_return_404_json() {
    $response = base_return_json(404, '资源不存在');
    return $response;
}

/**
 * 因为某一键名的值不能重复，删除重复项
 * @param $arr
 * @param $key
 * @return mixed
 */
function assoc_unique($arr, $key)
{
    $tmp_arr = array();
    foreach ($arr as $k => $v) {
        if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            unset($arr[$k]);
        } else {
            $tmp_arr[] = $v[$key];
        }
    }
    sort($arr); //sort函数对数组进行排序
    return $arr;
}

/**
 * Notes: 抛出json
 * @param int $code
 * @param string $msg
 * @param array $data
 */
function base_throw_json($code = 500, $msg = '', $data = [])
{
    $response = $code instanceof Response ? $code :
        json(['code' => $code, 'msg' => $msg, 'data' => $data], 200, [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'POST, PUT, GET, OPTIONS, DELETE',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Headers' => 'x-auth-token, x-requested-with,Authorization,Origin, Accept, Content-Type,x-xsrf-token'
        ]);
    throw new HttpResponseException($response);
}

/**
 * Notes: 抛出错误json
 * @param string $msg
 */
function base_throw_error_json($msg = '')
{
    $response = base_return_json(10005, $msg);
    base_throw_json($response);
}

/**
 * Notes: 抛出成功json
 * @param array $data
 */
function base_throw_success_json($data = [])
{
    $response = base_return_json(10000, \think\facade\Lang::get('successful'), $data);
    base_throw_json($response);
}

/**
 * Notes: 生成指定长度的随机字符串
 * @param int $len
 * @return null|string
 */
function base_rand_char($len = 32)
{
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;
    for ($i = 0; $i < $len; $i++) {
        $str .= $strPol[rand(0, $max)];
    }
    return $str;
}
/**
 *邀请码
 */
function initcode() {
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $rand = $code[rand(0,25)]
        .strtoupper(dechex(date('m')))
        .date('d').substr(time(),-5)
        .substr(microtime(),2,5)
        .sprintf('%02d',rand(0,99));
    for(
        $a = md5( $rand, true ),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
        $d = '',
        $f = 0;
        $f < 5;
        $g = ord( $a[ $f ] ),
        $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
        $f++
    );
    if(recode($d)){
        return $d;
    }else{
        initcode();
    }

}

function recode($code) {
    if (Db::table("eft_technician_member")->where("invite_code",'eq',$code)->find()) {
        return false;
    }
    return true;
}


/**
 * Notes: 生成一个 hash 串
 * @return string
 */
function base_hash_char()
{
    return md5(uniqid(md5(microtime(true)), true) . base_rand_char());
}

/**
 * Notes: 对字符串进行SQL注入过滤
 * @param string $string
 * @return string
 */
function base_sql_filter($string = '')
{
    if (!is_string($string) || !$string) return '';
    $string_old = $string;

    $string = str_ireplace("\\", "/", $string);
    $string = str_ireplace("\"", "/", $string);
    $string = str_ireplace("'", "/", $string);
    $string = str_ireplace("*", "/", $string);
    $string = str_ireplace("%5C", "/", $string);
    $string = str_ireplace("%22", "/", $string);
    $string = str_ireplace("%27", "/", $string);
    $string = str_ireplace("%2A", "/", $string);
    $string = str_ireplace("~", "/", $string);
    $string = str_ireplace("select", "\sel\ect", $string);
    $string = str_ireplace("insert", "\ins\ert", $string);
    $string = str_ireplace("update", "\up\date", $string);
    $string = str_ireplace("delete", "\de\lete", $string);
    $string = str_ireplace("union", "\un\ion", $string);
    $string = str_ireplace("into", "\in\to", $string);
    $string = str_ireplace("load_file", "\load\_\file", $string);
    $string = str_ireplace("outfile", "\out\file", $string);
    $string = str_ireplace("sleep", "\sle\ep", $string);
    $string = strip_tags($string);
    if ($string_old != $string) $string = '';
    return trim($string);
}

//去除二维数组中的重复项
function remove_duplicate($array)
{
    $result = array();
    for ($i = 0; $i < count($array); $i++) {
        $source = $array[$i];
        if (array_search($source, $array) == $i && $source <> "") {
            $result[] = $source;
        }
    }
    return $result;
}

/**
 * 获取订单编号
 */
function msectimeCode($id=null,$length=15)
{
    if(empty($id)){
        $string = rand(100, 999).time().rand(100, 999);
    }else{
        $string = $id. time() . rand(1000, 9999);
    }
    return substr($string,0,$length);
}

//返回当前的毫秒时间戳
function msectime()
{
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}

//处理产品轮播图string=>array
function strImgArr($img)
{
    $arr = [];
    if (!empty($img)) {
        $arr = explode('|', $img);
    }
    return $arr;
}

//处理产品轮播图 array=>string
function arrImgStr($img)
{
    $image_string = '';
    foreach (maybe_json_decode($img) as $key => $value) {
        if (empty($image_string)) {
            $image_string = $value;
        } else {
            $image_string = $image_string . '|' . $value;
        }
    }
    return $image_string;
}

/**
 * 计算两点地理坐标之间的距离
 * @param Decimal $longitude1 起点经度
 * @param Decimal $latitude1 起点纬度
 * @param Decimal $longitude2 终点经度
 * @param Decimal $latitude2 终点纬度
 * @param Int   $unit    单位 1:米 2:公里
 * @param Int   $decimal  精度 保留小数位数
 * @return Decimal
 */
function getDistance($longitude1=0, $latitude1=0, $longitude2=0, $latitude2=0, $unit=1, $decimal=2){

    $EARTH_RADIUS = 6378.137; // 地球半径系数
    $PI = 3.1415926;

    $radLat1 = (float)$latitude1 * $PI / 180.0;
    $radLat2 = (float)$latitude2 * $PI / 180.0;

    $radLng1 = (float)$longitude1 * $PI / 180.0;
    $radLng2 = (float)$longitude2 * $PI /180.0;

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $distance = $distance * $EARTH_RADIUS * 1000;

    if($unit==2){
        $distance = $distance / 1000;
    }

    return round($distance, $decimal);

}

/**
 * @param $lng
 * @param $lat
 * @param float $distance 单位：km
 * @return array
 * 根据传入的经纬度，和距离范围，返回所有在距离范围内的经纬度的取值范围
 */
function location_range($lng, $lat,$distance = 0.5){
    $earthRadius = 6378.137;//单位km
    $d_lng =  2 * asin(sin($distance / (2 * $earthRadius)) / cos(deg2rad($lat)));
    $d_lng = rad2deg($d_lng);
    $d_lat = $distance/$earthRadius;
    $d_lat = rad2deg($d_lat);
    return array(
        'lat_start' => $lat - $d_lat,//纬度开始
        'lat_end' => $lat + $d_lat,//纬度结束
        'lng_start' => $lng-$d_lng,//纬度开始
        'lng_end' => $lng + $d_lng//纬度结束
    );
}

/**
 *数字金额转换成中文大写金额的函数
 *String Int  $num  要转换的小写数字或小写字符串
 *return 大写字母
 *小数位为两位
 **/
function toChineseNumber($num){
    $c1 = "零壹贰叁肆伍陆柒捌玖";
    $c2 = "分角元拾佰仟万拾佰仟亿";
    $num = round($num, 2);
    $num = $num * 100;
    if (strlen($num) > 10) {
        return "数据太长，没有这么大的钱吧，检查下";
    }
    $i = 0;
    $c = "";
    while (1) {
        if ($i == 0) {
            $n = substr($num, strlen($num)-1, 1);
        } else {
            $n = $num % 10;
        }
        $p1 = substr($c1, 3 * $n, 3);
        $p2 = substr($c2, 3 * $i, 3);
        if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
            $c = $p1 . $p2 . $c;
        } else {
            $c = $p1 . $c;
        }
        $i = $i + 1;
        $num = $num / 10;
        $num = (int)$num;
        if ($num == 0) {
            break;
        }
    }
    $j = 0;
    $slen = strlen($c);
    while ($j < $slen) {
        $m = substr($c, $j, 6);
        if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
            $left = substr($c, 0, $j);
            $right = substr($c, $j + 3);
            $c = $left . $right;
            $j = $j-3;
            $slen = $slen-3;
        }
        $j = $j + 3;
    }

    if (substr($c, strlen($c)-3, 3) == '零') {
        $c = substr($c, 0, strlen($c)-3);
    }
    if (empty($c)) {
//        return "零元整";
        return "零元";
    }else{
//        return $c . "整";
        return $c;
    }
}

//生成编码（邀请码）
function uuid($prefix = '',$num=5) {
    $chars = bin2hex(openssl_random_pseudo_bytes($num));
    return $prefix . $chars;
}
/**
 * 输出文本内容
 *
 * @since v1.0.0
 * @author ranj
 * @param string $content 内容
 * @return Response
 */
function content($content){
    $response = new Response();
    $response->content($content);
    $response->contentType("text/plain");
    return $response;
}

/**
 * 导出
 * @param $filename
 * @param array $tileArray
 * @param array $dataArray
 */
function exportToExcel($filename, $tileArray = [], $dataArray = []){
    require_once $_SERVER['DOCUMENT_ROOT']."/../extend/org/PHPExcel/Classes/PHPExcel.php";
    $excel = new PHPExcel();
    $objDrawing = new PHPExcel_Worksheet_Drawing();

    $excel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $excel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
    $objActSheet = $excel->getActiveSheet();

    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');

    $tableheader = $tileArray;

    for($i = 0;$i < count($tableheader);$i++) {
        $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
    }
    $data = $dataArray;
    for ($i = 0;$i < count($data);$i++) {
        $j = $i + 2;
        for ($row = 0;$row < count($data[$i]);$row++) {
            //设置列的宽度
            $objActSheet->getColumnDimension("$letter[$row]")->setWidth(20);
            //设置行的高度
            $excel->getActiveSheet()->getRowDimension($j)->setRowHeight(15);
            $excel->getActiveSheet()->setCellValue("$letter[$row]$j",$data[$i][$row]);
//            if ($row == 3&&!is_null_or_empty($data[$i][$row])) {
//                // 创建图片操作对象
//                $objDrawing = new PHPExcel_Worksheet_Drawing();
//                //设置图片路径
//                $objDrawing->setPath($data[$i][$row]);
//                // 设置图片高
//                $objDrawing->setHeight(100);
//                //设置图片插入位置
//                $objDrawing->setCoordinates("$letter[$row]$j");
//                // 设置图片偏移量
//                $objDrawing->setOffsetX(20);
//                $objDrawing->setOffsetY(18);
//                // 设置图片倾斜
//                $objDrawing->setRotation(80);
//                $objDrawing->getShadow()->setVisible(true);
//                $objDrawing->getShadow()->setDirection(50);
//                //得到当前工作表对象
//                $ActiveSheet=$excel->getActiveSheet();
//                //添加到工作表
//                $objDrawing->setWorksheet($ActiveSheet);
//                continue;
//            }else{
//                $excel->getActiveSheet()->setCellValue("$letter[$row]$j",$data[$i][$row]);
//            }

        }
    }
    $write = new PHPExcel_Writer_Excel5($excel);
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
    header("Content-Type:application/force-download");
    header("Content-Type:application/vnd.ms-execl");
    header("Content-Type:application/octet-stream");
    header("Content-Type:application/download");;
    header('Content-Disposition:attachment;filename="'.$filename.'.xlsx"');
    header("Content-Transfer-Encoding:binary");
    $write->save('php://output');
    exit;
}

function exportToExcel2($filename, $tileArray = [], $dataArray = [])
{
    ini_set('memory_limit', '512M');
    ini_set('max_execution_time', 0);
    ob_end_clean();
    ob_start();
    header("Content-Type: text/csv");
    header("Content-Disposition:filename=" . $filename. ".xls");
    $fp = fopen('php://output', 'w');
    fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
    //        $fp=fopen('D://hello.csv','w');
    fputcsv($fp, $tileArray);
    $index = 0;
    foreach ($dataArray as $item) {
        if ($index == 1000) {
            $index = 0;
            ob_flush();
            flush();
        }
        $index++;
        fputcsv($fp, $item);
    }

    ob_flush();
    flush();
    ob_end_clean();
}

function doRequest($url, $param=array(), $timeout = 60*60){
    $urlParmas = parse_url($url);
    $host = $urlParmas['host'];
    $path = $urlParmas['path'];
    $port = isset($urlParmas['port']) ? $urlParmas['port'] : 443;
   /* if($urlParmas['scheme'] == 'https'){
        $host= 'ssl://'.$host;
    }*/
    $errno = 0;
    $errstr = '';
    $fp = fsockopen('ssl://'.$host, $port, $errno, $errstr, $timeout);
    $query = isset($param) ? http_build_query($param) : '';
    stream_set_blocking($fp, 0);
    stream_set_timeout($fp, 1);
    $out = "POST " . $path . " HTTP/1.1\r\n";
    $out .= "host:" . $host . "\r\n";
    $out .= "content-length:" . strlen($query) . "\r\n";
    $out .= "content-type:application/x-www-form-urlencoded\r\n";
    $out .= "connection:close\r\n\r\n";
    $out .= $query;
    $result = fwrite($fp, $out);
//   sleep($timeout);// 函数延迟执行当前脚本若干秒。
    usleep(10000);// 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。
    fclose($fp);
    \think\facade\Log::error($result);
    return $result;
}







